import { createStore } from 'vuex'

export default createStore({
   state: {
      cartarray: []
   },
   mutations: {
      //添加商品到购物车
      tocart(state: any, tag: any) {
         //判断是否存在购物车里面
         const goods: any = state.cartarray.find((val: any) => {
            return val.id == tag.id
         })
         if (goods) {  //不为空就购物车不存在一样的商品
            goods.cartCount += 1
         } else {  //不为空的话就添加
            const item = {
               id: tag.id,
               title: tag.details,
               cartCount: 1,
               img: tag.img
            }
            state.cartarray.push(item)
         }
         console.log(tag + '我在Vuex中')
      },


      getcart(state: any) {
         console.log(state.cartarray)
      },
      //清空
      clearCart(state: any) {
         state.cartarray = [];
      },
      //数量添加
      add(state: any, tag: any) {
         //判断cartarray的id 是否有和他传过来的tagID 如果有就是在购物车里面有 
         const goods: any = state.cartarray.find((val: any) => {
            return val.id == tag.id;
         })
         //判断goods 是否存在  
         if (goods) {
            goods.cartCount += 1;
         } else {
            const item = {
               id: tag.id,
               title: tag.title,
               cartCount: 1,
               img: tag.img
            }
            //不存在则push到购物车数组中
            state.cartarray.push(item);
         }
      },
      // 减少商品
      substract(state: any, val: any) {

         for (let i = 0; i < state.cartarray.length; i++) {
            if (state.cartarray[i].id == val.id) {
               if (state.cartarray[i].cartCount == 1) {
                  state.cartarray.splice(i, 1);
               } else {
                  state.cartarray[i].cartCount -= 1;
               }
            }
         }
      }
   },
   actions: {
   },
   modules: {
   },
   getters: {
      getGoodsNum(store: any) {
         let num = 0;
         store.cartarray.forEach((val: any) => {
            num += val.cartCount;
         });


         return num;
      }
   }
})
